package cn.fl.fgi.service.impl;

import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.dto.SysUsrDTO;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.fgi.api.IFgiGuarRateApiService;
import cn.fl.fgi.api.dto.FgiGuarRateDTO;
import cn.fl.fgi.service.IFgiGuarRateService;
import cn.fl.fgi.transform.FgiGuarRateVOTransform;
import cn.fl.fgi.vo.FgiGuarRateVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.service.ISysUsrService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 商家活动记录表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class FgiGuarRateServiceImpl implements IFgiGuarRateService {

    /**
     * TODO 自定义 API 暴露服务
     */
    @Autowired
    private IFgiGuarRateApiService fgiGuarRateApiService;

    @Autowired
    private ISysUsrApiService sysUsrApiService;

    @Override
    public FgiGuarRateVO selectById(Long id) throws BaseException {
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        //TODO 业务逻辑
        FgiGuarRateDTO dto = null;//this.自定义ApiService.selectById(id);
        return FgiGuarRateVOTransform.toVO(dto);
    }

    @Override
    public FgiGuarRateVO selectByProgramNo(String programNo) throws BaseException {
        FgiGuarRateDTO qc = new FgiGuarRateDTO();
        qc.setProgramNo(programNo);
        try {
            List<FgiGuarRateDTO> fgiGuarRateDTOS = this.fgiGuarRateApiService.selectList(JSON.toJSONString(qc));
            FgiGuarRateVO vo = FgiGuarRateVOTransform.toVO(fgiGuarRateDTOS.get(0));

            StringBuilder orgNms = null;
            StringBuilder busTypes = null;
            for (FgiGuarRateDTO dto : fgiGuarRateDTOS) {
                if (null == orgNms) {
                    orgNms = new StringBuilder();
                    orgNms.append(dto.getOrgNm());
                } else {
                    if (!orgNms.toString().contains(dto.getOrgNm())) {
                        orgNms.append("<br/>").append(dto.getOrgNm());
                    }
                }
                if (null == busTypes) {
                    busTypes = new StringBuilder();
                    busTypes.append(dto.getBusType());
                } else {
                    if (!busTypes.toString().contains(dto.getBusType())) {
                        busTypes.append(";").append(dto.getBusType());
                    }
                }
            }

            vo.setOrgNm(orgNms.toString());
            vo.setBusType(busTypes.toString());
            if (StringUtils.isEmpty(vo.getOverdueBeginDay()) && StringUtils.isEmpty(vo.getOverdueEndDay())) {
                vo.setOverdueBeginDayToEnd("----");
            } else {
                vo.setOverdueBeginDayToEnd(vo.getOverdueBeginDay() + "~~" + vo.getOverdueEndDay());
            }
            if (null == vo.getOrgPayBegin() && null == vo.getOrgPayEnd()) {
                vo.setOrgPayBeginToEnd("----");
            } else {
                vo.setOrgPayBeginToEnd(DateUtils.formatDateToString(vo.getOrgPayBegin(), DateUtils.YYYY_MM_DD) + "~~"
                        + DateUtils.formatDateToString(vo.getOrgPayEnd(), DateUtils.YYYY_MM_DD));
            }
			if (null == vo.getRepBegin() && null == vo.getRepEnd()) {
				vo.setRepBeginToEnd("----");
			} else {
				vo.setRepBeginToEnd(DateUtils.formatDateToString(vo.getRepBegin(), DateUtils.YYYY_MM_DD) + "~~"
						+ DateUtils.formatDateToString(vo.getRepEnd(), DateUtils.YYYY_MM_DD));
			}
			if (null == vo.getEnableBegin() && null == vo.getEnableEnd()) {
				vo.setEnableBeginToEnd("----");
			} else {
				vo.setEnableBeginToEnd(DateUtils.formatDateToString(vo.getEnableBegin(), DateUtils.YYYY_MM_DD) + "~~"
						+ DateUtils.formatDateToString(vo.getEnableEnd(), DateUtils.YYYY_MM_DD));
			}
			return vo;
        } catch (IllegalAccessException e) {
            BaseLogUtils.newWebLogger("查询异常").setLogOperType(LogOperEnum.RESP)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setWarning(false)
                    .setThrowable(e)
                    .error(BaseExceptionConstant.COMMON_0002_NAME);
        } catch (Exception ex) {
            BaseLogUtils.newWebLogger("查询异常").setLogOperType(LogOperEnum.RESP)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setWarning(false)
                    .setThrowable(ex)
                    .error(BaseExceptionConstant.COMMON_0002_NAME);
        }
        return null;
    }

    @Override
    public Long add(FgiGuarRateVO entity) throws BaseException {
        if (null == entity) {
            return null;
        }
        //return this.splActivityRecApiService.add(SplActivityRecVOTransform.toDTO(entity));
        //TODO 业务逻辑
        return null;
    }

    @Override
    public boolean batchAdd(List<FgiGuarRateVO> list) throws BaseException {
        return this.fgiGuarRateApiService.batchAdd(FgiGuarRateVOTransform.toDTOList(list));
    }

    @Override
    public boolean removeById(Long id) throws BaseException {
        if (StringUtils.isEmpty(id)) {
            return false;
        }
        //return this.splActivityRecApiService.removeById(id);
        //TODO 业务逻辑
        return false;
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    public boolean removeByIds(List<Long> ids) throws BaseException {
        if (CollectionUtils.isEmpty(ids)) {
            return false;
        }
        ;
        return false;
    }

    @Override
    public boolean modify(FgiGuarRateVO entity) throws BaseException {
        if (null == entity) {
            return false;
        }
        //return this.splActivityRecApiService.modify(SplActivityRecVOTransform.toDTO(entity));
        //TODO 业务逻辑
        return false;
    }

    @Override
    public Pager searchListPage(Pager page) throws BaseException, IllegalAccessException {
        if (null == page) {
            page = new Pager();
        }
        if (null == page.getCondition()) {
            FgiGuarRateDTO splActivityRecQC = new FgiGuarRateDTO();
            page.setCondition(splActivityRecQC);
        }
        String pageStr = JSON.toJSONString(page);
        String resultStr = this.fgiGuarRateApiService.selectListPage(pageStr);
        JSONObject jsonObject = JSON.parseObject(resultStr);
        List<FgiGuarRateDTO> records = JSON.parseArray(jsonObject.get("records").toString(), FgiGuarRateDTO.class);

        List<Long> usrIdList = new ArrayList<>();
        for (FgiGuarRateDTO record : records) {
            if (!usrIdList.contains(record.getCrtUsrId())) {
                usrIdList.add(record.getCrtUsrId());
            }
        }
        List<SysUsrDTO> sysUsrDTOS = this.sysUsrApiService.selectSysUserInfoList(usrIdList);
        Map<Long, String> usrMap = new HashMap<>(sysUsrDTOS.size());
        for (SysUsrDTO sysUsrDTO : sysUsrDTOS) {
            usrMap.put(sysUsrDTO.getId(), sysUsrDTO.getRefRlNm());
        }

        List<FgiGuarRateVO> voList = FgiGuarRateVOTransform.toVOList(records);
        for (FgiGuarRateVO vo : voList) {
            vo.setCrtUsrNm(usrMap.get(vo.getCrtUsrId()));
        }

        Integer total = jsonObject.getInteger("total");
        Pager pager = new Pager();
        pager.setResultList(voList);
        pager.setTotalCount(total);
        return pager;
    }

    @Override
    public List<FgiGuarRateVO> searchList(String conditionStr) throws BaseException {
        if (null == conditionStr) {
            return null;
        }
        return null;// todo SplActivityRecVOTransform.toVOList(this.splActivityRecApiService.searchList(condition));
    }

    @Override
    public boolean beInvalid(List<Long> ids) throws BaseException {
        return this.fgiGuarRateApiService.beInvalidByIds(ids, CurrentThreadContext.getCurrentUserId());
    }

    @Override
    public List<KeyValueVO> getBusSourceTypeMap() {
        Map<String, String> map = this.fgiGuarRateApiService.getBusSourceTypeMap();
        List<KeyValueVO> list = new ArrayList<>(map.size());
        for (Map.Entry<String, String> entry : map.entrySet()) {
            KeyValueVO vo = new KeyValueVO();
            vo.setKey(entry.getKey());
            vo.setValue(entry.getValue());
            list.add(vo);
        }
        return list;
    }
}
